#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, Integer, String, Unicode, UnicodeText, DateTime, TIMESTAMP, func
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()
Session.configure(bind=engine)

"""user_brief collection has
   userid:     用户的userid (int)
   name:       用户名（string）
   intro：     用户简介（string）
   zone：      用户空间名（string）
   imglink：  用户头像链接（string）
   utime：     资料最后更新时间（datetime）
"""


class UserBriefItem(object):

    def to_dict(self):
        res = {}
        res['userid'] = self.userid
        res['name'] = self.name
        res['intro'] = self.intro
        res['zone'] = self.zone
        res['imglink'] = self.imglink
        res['utime'] = self.utime.strftime("%Y-%m-%d %H:%M:%S")\
            if self.utime else ""

        return res

    def __repr__(self):
        return "%d" % (self.userid)


user_brief_table = Table(
    'user_brief', metadata,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('userid', Integer, index=True, nullable=False),
    Column('name', Unicode(65), nullable=False),
    Column('intro', UnicodeText, nullable=False),
    Column('zone', Unicode(65), nullable=False),
    Column('imglink', UnicodeText, nullable=False),
    Column('utime', TIMESTAMP, server_default=func.now(), server_onupdate=func.current_timestamp())
)

mapper(UserBriefItem, user_brief_table)

def create_user_brief_table_if_not_exist():
    metadata.create_all(engine)

def add_user_brief_item(p_item):
    item = UserBriefItem()
    item.userid = p_item['userid']
    item.name = p_item['name']
    item.intro = p_item['intro']
    item.zone = p_item['zone']
    item.imglink = p_item['imglink']

    try:
        session = Session()
        session.add(item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_user_brief_by_userid(p_userid):
    try:
        session = Session()
        user_brief = session.query(UserBriefItem) \
            .filter_by(userid=p_userid).first()
        if user_brief is None:
            return None
        return user_brief.to_dict()
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_user_brief_by_userid_list(p_userid_list):
    try:
        session = Session()
        user_brief_list = session.query(UserBriefItem)\
            .filter(UserBriefItem.userid.in_(p_userid_list))\
            .all()
        return [u.to_dict() for u in user_brief_list]
    except Exception as e:
        log.exp(e)
        session.rollback()
        return []
    finally:
        session.close()

def get_user_brief_map_by_userid_list(p_userid_list):
    try:
        session = Session()
        user_brief_list = session.query(UserBriefItem)\
            .filter(UserBriefItem.userid.in_(p_userid_list))\
            .all()

        return {u.userid: u.to_dict() for u in user_brief_list}
    except Exception as e:
        log.exp(e)
        session.rollback()
        return []
    finally:
        session.close()

def update_user_brief_by_userid(p_userid, p_intro, p_zone):
    try:
        intro = p_intro
        zone = p_zone
        session = Session()
        item = session.query(UserBriefItem).filter_by(userid=p_userid).all()
        if item is None:
            brief_item = {
                "intro": intro,
                "zone": zone
            }
            add_user_brief_item(brief_item)
        else:
            session.query(UserBriefItem).filter_by(userid=p_userid).update({"intro": intro, "zone": zone})
            session.flush()
            session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_square_users(p_begin, p_limit, p_current_userid_list):
    try:
        session = Session()
        square_users_list = session.query(UserBriefItem) \
            .filter(UserBriefItem.userid.notin_(p_current_userid_list)) \
            .order_by(UserBriefItem.utime.desc()).offset(p_begin).limit(p_limit).all()
        result = [item.to_dict() for item in square_users_list]
        return result
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def update_fake_user_brief_by_userid(p_userid, p_item):
    try:
        session = Session()
        session.query(UserBriefItem).filter_by(userid=p_userid).update(p_item)
        session.flush()
        session.commit()
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

def get_all_user_brief_except_black(p_begin, p_limit, p_black_userid_list):
    try:
        session = Session()
        user_brief = session.query(UserBriefItem) \
            .filter(UserBriefItem.userid.notin_(p_black_userid_list)) \
            .offset(p_begin).limit(p_limit).all()
        if user_brief is None:
            return None
        return [item.to_dict() for item in user_brief]
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


def get_user_count():
    try:
        session = Session()
        item = session.query(func.count(UserBriefItem.userid)).first()
        return item[0] if item else None
    except Exception as e:
        log.exp(e)
        session.rollback()
        return None
    finally:
        session.close()

if __name__ == "__main__":
    create_user_brief_table_if_not_exist()